<template>
    <!-- 信道可用分析 -->
    <div>
        <div class="width100 height100" :class="layout == 'one' ? 'flex one' : 'flex-column all'">
            <div class="flex-column" :class="layout == 'one' ? 'flex1' : 'flex2'">
                <!-- 频谱图 -->
                <div class="back flex1 chart" :id="chart1"></div>
                <!-- 瀑布图 -->
                <div class="back flex1 chart" :id="chart2">
                </div>
            </div>
            <!-- 信道可用性 -->
            <div class="back flex1 chart" :id="chart3"></div>
        </div>
    </div>
</template>

<script>
import * as echarts from "echarts";

export default {
    name: 'pageAnalyse',
    emits: [],
    components: {},
    props: {
        // 布局类型
        layout: { type: String, default: 'one' },
        showClass: { type: Boolean },
        change: {},
        socketObj: { type: Object, default: () => { } }
    },
    computed: {
        socketStatus() {
            if (!this.socketObj) return false;
            if (this.socketObj.socket.readyState == 1) return true;
            return false
        }
    },
    watch: {
        change() {
            this.$nextTick(() => {
                setTimeout(this.chartResize, 10);
                // 更新插件
                // setTimeout(this.initLotDom, 10)
            })
        },
        socketStatus(val) {
            if (val) this.socketBack();
        },
    },
    data() {
        return {
            // 频谱图id
            chart1: null,
            // 频谱图
            snrChart: null,
            // 瀑布图id
            chart2: null,
            // 信道可用性分析图id
            chart3: null,

        }
    },
    created() {
        this.chart1 = this.$uuid(); // 频谱图
        this.chart2 = this.$uuid(); // 瀑布图
        this.chart3 = this.$uuid(); // 信道可用性分析图
    },
    mounted() {
        this.$nextTick(() => {
            setTimeout(this.initChart, 100)
            // 开启更新
            // setInterval(this.updateCharts,200)

            // initEnviroment({
            //     success: () => {
            //         setTimeout(this.initLotDom, 1000)
            //     },
            //     error: er => {
            //         console.log("失败")
            //     }
            // });
        })
    },
    methods: {
        // 初始化socket返回处理函数
        initUpdateBack() {
            if (!this.socketObj) return;
            this.socketBack()
        },
        // 设置socket回调函数
        socketBack() {
            this.socketObj.setMsgBack({
                cmd: 'push-full',
                fun: rs => {
                    // console.log("收到了频谱图数据:", rs)
                    const result = this.formartResult(rs.data);
                    // 信号强度集合
                    let ampList = result['amp'];
                    // 频率集合
                    let freqList = result['freq'];
                    // 如果信号强度集合与频率没有一一对应起来则是错误的数据
                    if (ampList.length == freqList.length) {
                        // 数据处理
                        let list = [];
                        for (let i = 0; i < ampList.length; i++) list.push([freqList[i]/10**3, ampList[i]]);
                        this.updateCharts(list)
                    } else {
                        // console.log("频谱图数据异常:", rs)
                        return;
                    }
                },
            })
        },
        // socket数据过滤统一处理
        formartResult(result) {
            let {dataLables, data} = result;
            let resultMap = {};
            if(dataLables.length != data.length) {
                console.log("数据解析失败:", result)
                return resultMap
            }else{
                for(let i = 0; i < dataLables.length; i++) {
                    resultMap[dataLables[i]] = data[i]
                }
            }
            return resultMap
        },
        // 过滤数据算法从1px宽度中最多取出3个点的数据,先保留着
        foramrtList(list, space) {
            let resultList = [];
            let startDate = new Date()
            while (list.length > 0) {
                var olist = list.splice(0, space);
                var x = olist.map(item => item[0])
                var y = olist.map(item => item[1])
                var maxY = Math.max(...y);
                var maxX = x[y.indexOf(maxY)];
                var minY = Math.min(...y);
                var minX = x[y.indexOf(minY)];
                resultList.push(olist[0])
                if (maxX > minX) {
                    if (minX != olist[0][0]) resultList.push([minX, minY])
                    if (maxX != olist[0][0] && maxX != minX) resultList.push([maxX, maxY])
                } else {
                    if (maxX != olist[0][0]) resultList.push([maxX, maxY])
                    if (minX != olist[0][0] && minX != maxX) resultList.push([minX, minY])
                }
                var last = olist[olist.length - 1];
                if (last[0] != olist[0][0] && last[0] != minX && last[0] != maxX)
                    resultList.push(olist[olist.length - 1])
                // console.log(olist)
                // console.log(` maxX:${maxX}: maxY:${maxY}\n minX:${minX}: minY:${minY}\n`)
            }
            let endDate = new Date();
            console.log("耗时：", (endDate - startDate) / 1000)
            return resultList;
        },
        // 初始化频谱图dom
        initChart(datas = []) {
            if (!this.snrChart) this.snrChart = echarts.init(document.getElementById(this.chart1));
            this.snrChart.setOption({
                legend: {},
                grid: {
                    containLabel: false,
                    show: true,
                    backgroundColor: 'black',
                    left: '50',
                    bottom: '40',
                    right: '30',
                    top: '40'
                },
                xAxis: [
                    {
                        type: 'value',
                        scale: true,
                        name: 'FREQ(KHz)',
                        nameGap: 10,
                        nameRotate: 90,
                        boundaryGap: false,
                        axisLine: { onZero: false },
                        splitLine: { show: false },
                    }
                ],
                yAxis: {
                    type: 'value',
                    // scale: true,
                    name: `Magnitude\nResponse(dB)`,
                    nameGap: 10,
                    nameRotate: 0,
                    nameTextStyle: {
                        padding: [50, 0, 0, 0],
                        rich: {}
                    },
                    // boundaryGap: ['0%', '0%'],
                    axisLine: { onZero: false },
                    splitLine: { show: false },
                    max: 50,
                    min: -150
                },
                // dataZoom: [{ type: 'inside', start: 0, end: 10 }, { start: 0, end: 10 }],
                series: [
                    // {
                    //     name: '原数据',
                    //     type: 'line',
                    //     showSymbol: false,
                    //     connectNulls: true,
                    //     lineStyle: {
                    //         color: 'red',
                    //         width: 1 // 设置线条宽度，加粗度
                    //     },
                    //     connectNulls: true,
                    //     data: listObj,
                    // },
                    {
                        name: '过滤后',
                        type: 'line',
                        showSymbol: false,
                        connectNulls: true,
                        smooth: true,
                        lineStyle: {
                            color: '#857120',
                            width: 1 // 设置线条宽度，加粗度
                        },
                        connectNulls: true,
                        data: datas,
                    },

                ]
            });

            this.initUpdateBack();
        },
        // 更新折线图
        updateCharts(datas) {
            if (!this.snrChart) {
                this.initChart(datas);
            } else {
                this.snrChart.setOption({
                    series: [{ data: datas }]
                })
            }
        },
        // 加载插件
        initLotDom() {
            console.log("开始渲染插件")
            initLot([
                {
                    dom: document.getElementById(this.chart2),
                    type: "time",//validate: ['time', 'spectum', 'waterfall',  'mesh'];
                    name: this.chart2
                },
                {
                    dom: document.getElementById(this.chart3),
                    type: "time",//validate: ['time', 'spectum', 'waterfall',  'mesh'];
                    name: this.chart3
                }
            ])
        },
        // 适配图像
        chartResize() {
            if (!this.snrChart) {
                this.initChart()
            } else {
                this.snrChart.resize()
            }
        },
        // remove() {
        //     let dom = document.getElementById(`time${this.chart1}`)
        //     console.log("dom:", dom)
        //     qtLoader.removeCanvasElement(dom)
        // },
    },
    beforeDestroy() {
        if(this.socketObj) this.socketObj.removeMsgBack({cmd: 'push-full'})
        // console.log(`time${this.chart1}`,"qtLoader:",qtLoader)
        // let dom = document.getElementById(`time${this.chart1}`)
        // console.log("dom:",dom)
        // qtLoader.removeCanvasElement(dom)
    },
}
</script>

<style lang="scss" scoped></style>